package com.stt.mapper;

import com.stt.entity.Enrollment;
import org.apache.ibatis.annotations.*;
import java.util.List;

@Mapper
public interface EnrollmentMapper {

    @Insert("INSERT INTO enrollments(user_id, course_id) VALUES(#{userId}, #{courseId})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(Enrollment enrollment);

    // 根据id查询选课记录及关联的学生和课程信息
    @Select("SELECT e.*, u.username as student_name, c.name as course_name " +
            "FROM enrollments e " +
            "LEFT JOIN users u ON e.user_id = u.id " +
            "LEFT JOIN courses c ON e.course_id = c.id " +
            "WHERE e.id = #{id}")
    @Results({
        @Result(id = true, property = "id", column = "id"),
        @Result(property = "userId", column = "user_id"),
        @Result(property = "courseId", column = "course_id"),
        @Result(property = "student", column = "user_id",
                one = @One(select = "com.stt.mapper.UserMapper.findById")),
        @Result(property = "course", column = "course_id",
                one = @One(select = "com.stt.mapper.CourseMapper.findById"))
    })
    Enrollment findByIdWithDetails(Integer id);

    // 根据id查询某个学生的所有选课记录
    @Select("SELECT e.* FROM enrollments e WHERE e.user_id = #{userId}")
    @Results({
        @Result(id = true, property = "id", column = "id"),
        @Result(property = "userId", column = "user_id"),
        @Result(property = "courseId", column = "course_id"),
        @Result(property = "course", column = "course_id",
                one = @One(select = "com.stt.mapper.CourseMapper.findById"))
    })
    List<Enrollment> findByUserId(Integer userId);

    // 根据id查询某个课程的所有选课记录
    @Select("SELECT e.* FROM enrollments e WHERE e.course_id = #{courseId}")
    @Results({
        @Result(id = true, property = "id", column = "id"),
        @Result(property = "userId", column = "user_id"),
        @Result(property = "courseId", column = "course_id"),
        @Result(property = "student", column = "user_id",
                one = @One(select = "com.stt.mapper.UserMapper.findById"))
    })
    List<Enrollment> findByCourseId(Integer courseId);
}
